package org.example.climactic.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.json.JSONObject;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "迅雷云盘", description = "迅雷云盘相关接口")
@RestController
public class XunleiController {

    // 私有方法已移至类内部
    private String readCookieFromFile() {
        try {
            String cookie = new String(Files.readAllBytes(Paths.get("xunlei_cookie.txt")));
            System.out.println("读取到的 Cookie: " + cookie); // 添加日志
            return cookie;
        } catch (IOException e) {
            System.err.println("读取 cookie 文件失败: " + e.getMessage());
            return "";
        }
    }

    /**
     * 从 Cookie 中提取 authorized-token 的 accessToken
     * @param cookie Cookie 字符串
     * @return 提取到的 accessToken，若未找到则返回空字符串
     */
    private String extractAccessToken(String cookie) {
        if (cookie == null || cookie.isEmpty()) {
            return "";
        }

        // 查找 authorized-token= 后的内容
        String tokenPrefix = "authorized-token={\"accessToken\":\"";
        int startIndex = cookie.indexOf(tokenPrefix);
        if (startIndex == -1) {
            return "";
        }

        // 找到 accessToken 的起始位置
        startIndex += tokenPrefix.length();

        // 找到 accessToken 的结束位置（以 \" 结束）
        int endIndex = cookie.indexOf("\"", startIndex);
        if (endIndex == -1) {
            return "";
        }

        // 提取 accessToken
        return cookie.substring(startIndex, endIndex);
    }

    @Operation(summary = "获取迅雷云盘文件列表", description = "获取指定文件夹下的文件列表，默认获取根目录")
    @GetMapping("/api/xunlei/list")
    public ResponseEntity<String> getXunleiList(@RequestParam(defaultValue = "root") String parentId) {
        String url = "https://api-pan.xunlei.com/drive/v1/files?parent_id={parentId}&filters=%7B%22phase%22%3A%7B%22eq%22%3A%22PHASE_TYPE_COMPLETE%22%7D%2C%22trashed%22%3A%7B%22eq%22%3Afalse%7D%7D&with_audit=true&thumbnail_size=SIZE_SMALL&limit=50";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 从文件中读取 Cookie
        String cookie = readCookieFromFile().trim();
        cookie = cookie.replaceAll("[\\r\\n\\t]", "");
        
        // 提取 authorized-token 中的 accessToken
        String accessToken = extractAccessToken(cookie);
        
        // 添加认证请求头
        if (!accessToken.isEmpty()) {
            headers.add("Authorization", "Bearer " + accessToken);
        } else {
            headers.add("Cookie", cookie); // 回退到 Cookie
        }

        // 添加必要的请求头（确保包含浏览器捕获的所有头部）
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
        headers.add("Referer", "https://pan.xunlei.com/");
        headers.add("Origin", "https://pan.xunlei.com");
        headers.add("Sec-Fetch-Dest", "empty");
        headers.add("Sec-Fetch-Mode", "cors");
        headers.add("Sec-Fetch-Site", "same-origin");
        headers.add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        headers.add("Connection", "keep-alive");
        headers.add("device_id", "web");

        HttpEntity<String> entity = new HttpEntity<>(headers);

        RestTemplate restTemplate = new RestTemplate();
        HttpClient httpClient = HttpClientBuilder.create()
                .setRedirectStrategy(new DefaultRedirectStrategy() {
                    public boolean isRedirected(org.apache.http.HttpResponse response) {
                        return false;
                    }
                })
                .build();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        return response;
    }
}
